<template>
	<!-- 分享页面 -->
	<view class="page">
		<canvas id="myCanvas" canvas-id="myCanvas"
			style="height: 960rpx;width: 600rpx;position: fixed;top: -1000;left: -1000rpx;"></canvas>
	</view>
</template>

<script>
	const equal = uni.getSystemInfoSync().windowWidth / 750
	export default {
		name: "c-share",
		data() {
			return {
				canvasControl: null,
				tempFilePath: null,
				shareImg: ''
			};
		},
		onLoad() {},
		mounted() {

		},
		onShow() {},
		methods: {

			// 获取分享海报
			async getSharePosterFn() {
				uni.showLoading({
					title: '加载中...',
					mask: true,
					success: async () => {
						const {
							data
						} = await this.$api.shareApi()
						console.log('分享海报data', data);
						this.shareImg = data.shareImg
						this.drawPoster()
					}
				})
			},
			// 生成canvas
			drawPoster() {
				let imgBg = '/static/common/share-bg.png'
				this.canvasControl = uni.createCanvasContext('myCanvas', this)
				this.canvasControl.draw(true, setTimeout(_ => {
					// 背景
					this.canvasControl.drawImage(
						imgBg, 0, 0, 600 *
						equal,
						960 * equal)
					// 头像
					this.canvasControl.save()
					this.canvasControl.beginPath(); // 开始一个新的路径  
					const fs = wx.getFileSystemManager();
					//随机定义路径名称
					var times = new Date().getTime();
					var codeimg = wx.env.USER_DATA_PATH + '/' + times + '.png';
					//将base64图片写入
					fs.writeFile({
						filePath: codeimg,
						data: this.shareImg,
						encoding: 'base64',
						success: () => {
							this.canvasControl.drawImage(
								codeimg,
								(600 - 172) / 2 * equal,
								724 * equal,
								172 * equal,
								172 * equal)
							this.canvasControl.draw(true, () => {
								this.shareFn()
								uni.hideLoading()
							}, this)
						},
						fail: (err) => {}
					});
				}, 300))

			},
			// 分享
			shareFn() {
				let that = this
				if (this.tempFilePath) {
					wx.showShareImageMenu({
						path: this.tempFilePath,
					})
					return
				}
				uni.canvasToTempFilePath({
					canvasId: 'myCanvas',
					success: (res) => {
						that.tempFilePath = res.tempFilePath
						console.log('拉起分享');
						wx.showShareImageMenu({
							path: res.tempFilePath,
							success: () => {},
							fail: (err) => {
								console.log('err', err);
							}
						})
					},
					fail(err) {
						console.log('拉起分享失败', err);
					}
				}, this)
			},
		}
	};
</script>

<style lang="scss" scoped>

</style>